/*

c语言实现简单继承

  本示例展示了如何在C语言中模拟基本的继承特性：
  1. 通过结构体嵌套实现父类到子类的成员继承
  2. 使用函数指针实现方法重写
  3. 提供向上转型机制

 继承结构：
   Shape (父类)
     |
     +-- Circle (子类)  
*/

#include <stdio.h>
#include <stdlib.h>


// 父类：Shape 
typedef struct {
    void (*draw)(void*);   // 虚函数：绘制形状
    int x, y;
}Shape ;


void shape_draw(void* self) {
    Shape*shape = (Shape*)self;
    printf("Drawing generic shape at (%d, %d)\n", shape->x, shape->y);
}


void shape_init(Shape* shape, int x, int y) {
    shape->x = x;
    shape->y = y;
    shape->draw = shape_draw;
}


// 子类：Circle
typedef struct {
    Shape base;   // 继承Shape的成员
    int radius;   // 子类特有属性
}Circle;


// Circle的draw方法重写
void circle_draw(void* self) {
    Circle* circle = (Circle*)self;
    printf("Drawing circle at (%d, %d) with radius %d\n", circle->base.x, circle->base.y, circle->radius);
}


// Circle的构造函数
void circle_init(Circle* circle, int x, int y, int radius) {
    shape_init(&circle->base, x, y);
    circle->radius = radius;
}


// 类型转换函数
Shape* circle_to_shape(Circle* circle) {
    return &circle->base;   // 向上转型：子类指针转父类指针
}


int main() {
    // 创建Circle对象
    Circle circle;
    circle_init(&circle, 10, 20, 5);

    // 直接通过Circle对象调用draw方法
    circle.base.draw(&circle);

    // 向上转型：将Circle指针转换为Shape指针
    Shape* shape = circle_to_shape(&circle);
    shape->draw(shape);   // 调用父类的draw方法

    // 演示多态性: 通过父类指针调用子类的方法
    shape->draw = shape_draw;
    shape->draw(shape);   // 调用子类的draw方法

    return 0;
}
